﻿using DevExpress.Skins;
using DevExpress.UserSkins;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Windows.Forms;
using Autofac;
using SqlSugar.IOC;
using WinformDevelopFrame.Core.Autofac;
using WinformDevelopFrame.Common;
using WinformDevelopFrame.Core.Extend;
using Quartz.Impl;
using StackExchange.Redis;
using WinformDevelopFrame.Entity;

namespace WinformDevelopFrame
{
    internal static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            #region 容器
            // 创建容器
            var builder = new ContainerBuilder();
            // 注册 SqlSugar 配置
            builder.Register(c =>
            {
                var db = new SqlSugarClient(new ConnectionConfig
                {
                    ConnectionString = ConfigurationManager.AppSettings["SqlConnection"], // 设置数据库连接字符串
                    DbType = ConfigurationManager.AppSettings["DdType"] == IocDbType.MySql.ToString()
                        ? DbType.MySql
                        : DbType.SqlServer,
                    IsAutoCloseConnection = true,
                    InitKeyType = InitKeyType.Attribute // 如果使用实体类的属性进行主键标识，请设置为 InitKeyType.Attribute
                });
                return db;
            }).As<ISqlSugarClient>().InstancePerLifetimeScope();
            builder.RegisterModule(new AutofacModuleRegister());
            AppInfo.Container = builder.Build();
            #endregion

            #region Redis 订阅 用于管理在线用户

            // 建立 Redis 连接
            ConnectionMultiplexer redis = ConnectionMultiplexer.Connect(ConfigurationManager.AppSettings["Redis"]);
            // 获取订阅者
            ISubscriber subscriber = redis.GetSubscriber();
            // 订阅一个频道
            subscriber.Subscribe("Channel1", (channel, message) => {
                if (AppInfo.User.Id.ToString().Equals(message))
                {
                    "您已被强制下线，确定后将退出登录".ShowTips();
                    AppInfo.User.LoginStatus = LoginStatus.Logout;
                    AppInfo.Container.Resolve<ISqlSugarClient>().Updateable(AppInfo.User).ExecuteCommand();
                    Application.Exit();
                }
            });

            #endregion

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.ThreadException += Application_ThreadException;
            DevExpress.LookAndFeel.UserLookAndFeel.Default.SetSkinStyle(ConfigurationManager.AppSettings["SkinName"]);
            var frmLogin = AppInfo.Container.ResolveNamed<Form>("FrmLogin");
            if (frmLogin.ShowDialog() == DialogResult.OK)
            {
                Application.Run(AppInfo.Container.ResolveNamed<Form>("FrmMain"));
            }
        }
        private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs ex)
        {
            sysexceptionlog log=new sysexceptionlog();
            log.ExceptionContent = ex.Exception.Message;
            log.ExceptionTime=DateTime.Now;
            //获取本机IP并显示
            log.IP= System.Net.Dns.GetHostEntry(Environment.MachineName).AddressList[0].ToString();
            log.UserId = AppInfo.User.Id;
            AppInfo.Container.Resolve<ISqlSugarClient>().Insertable(log).ExecuteCommand();
            LogHelper.Error(ex.Exception.StackTrace);
            ex.Exception.StackTrace.ShowError();
        }
    }
}
